################################################################################
##
## Purpose: This script creates Figure 8
##
## Author: James Bisbee (james.h.bisbee@vanderbilt.edu)
##
## Input Files:
##  - ./data/prepped/finalData.RData: Prepped data from 9_DATA_final_build.R
##
## Output Files:
##  - ./output/figures/MS_figure_8.pdf
##
##
## See associated log file for compute environment, package versions, 
##  and date of most recent run.
##
################################################################################
rm(list = ls())
gc()
require(tidyverse)
require(ggridges)
require(fixest)
require(ggrepel)
require(patchwork)
require(marginaleffects)

set.seed(123)

# Compute details
print(paste0('Compute environment from ',Sys.Date(),' run by Bisbee'))
if(Sys.info()['sysname'] == 'Windows') {
  ram_size = system("wmic MemoryChip get Capacity", intern = TRUE)[-1]
  model_name = system("wmic cpu get name", intern = TRUE)[2] # nocov
  vendor_id = system("wmic cpu get manufacturer", intern = TRUE)[2] # nocov
  
  print(list(ram = stringr::str_squish(ram_size)[1],
             vendor_id = stringr::str_squish(vendor_id),
             model_name = stringr::str_squish(model_name),
             no_of_cores = parallel::detectCores()))
} else if(Sys.info()['sysname'] == 'Linuxs') {
  splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
  df <- do.call(rbind, lapply(splitted[-1], 
                              function(x) data.frame(
                                cpu = as.numeric(x[2]),
                                mem = as.numeric(x[4]),
                                pid = as.numeric(x[5]),
                                cmd = paste(x[-c(1:5)], collapse = " "))))
  df
} else {
  cat("If not on Linux or Windows, you'll have to figure out your own solution to seeing the compute environment.")
}

sessionInfo()


load('./data/prepped/finalData.RData')


# Rigorous fixed effects
dyadToAnal <- utterance_level %>%
  mutate_at(vars(matches('lag')),function(x) ifelse(is.na(x),0,x)) %>%
  mutate(votepct_rel = ifelse(is.infinite(votepct_rel),1,votepct_rel),
         respondingTo = relevel(factor(respondingTo),ref = 'FEDBERNANKE'))

dims <- colnames(utterance_level %>% select(matches('SENT_'),-matches('_lag|error')) %>% select(-matches('SEVERE|AUTHOR|LIKELY')))

summary(modAny <- feols(as.formula(paste0('interruptor ~ fedResp*yellenTime*anyDaughters',
                                          ' + nSons + interrupted + poly(year,3) + log(tot_utterances) + log(nchars_lag)',
                                          '| opensecretsID + chamber')),
                        utterance_level %>%
                          mutate(yellenTime = ifelse(yellenTime,1,0),
                                 anyDaughters = ifelse(nDaughters > 0,1,0)) %>%
                          filter(ind > mind,all > 30),
                        cluster = c('opensecretsID')))

summary(modAnyM <- feols(as.formula(paste0('interruptor ~ fedResp*yellenTime*anyDaughters',
                                           ' + nSons + interrupted + poly(year,3) + log(tot_utterances) + log(nchars_lag)',
                                           '| opensecretsID + chamber')),
                        utterance_level %>%
                          mutate(yellenTime = ifelse(yellenTime,1,0),
                                 anyDaughters = ifelse(nDaughters > 0,1,0)) %>%
                          filter(ind > mind,
                                 all > 30,
                                 gender == 'M'),
                        cluster = c('opensecretsID')))

summary(modAnyF <- feols(as.formula(paste0('interruptor ~ fedResp*yellenTime*anyDaughters',
                                           ' + nSons + interrupted + poly(year,3) + log(tot_utterances) + log(nchars_lag)',
                                           '| opensecretsID + chamber')),
                         utterance_level %>%
                           mutate(yellenTime = ifelse(yellenTime,1,0),
                                  anyDaughters = ifelse(nDaughters > 0,1,0)) %>%
                           filter(ind > mind,
                                  all > 30,
                                  gender == 'F'),
                         cluster = c('opensecretsID')))



toplotAny <- plot_cme(modAny,variables = 'fedResp',
                      condition = (c('yellenTime','anyDaughters')),draw = F)

toplotAny <- toplotAny %>%
  left_join(toplotAny %>%
              group_by(anyDaughters) %>%
              summarise(diff = diff(estimate),
                        se = sqrt(sum(std.error^2))) %>%
              ungroup()) %>%
  bind_cols(modAny$coeftable %>%
              data.frame() %>%
              mutate(vars = row.names(.)) %>%
              filter(grepl('.*:.*:.*',vars)) %>%
              as_tibble() %>%
              select(est = Estimate,pval = Pr...t..,stdErr = Std..Error))

pAny <- toplotAny %>%
  mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
  ggplot(aes(x = factor(yellenTime),y = estimate,group = anyDaughters,color = anyDaughters,shape = anyDaughters)) + 
  geom_errorbar(aes(ymin = conf.low,ymax = conf.high),width = 0,position = position_dodge(width = 0)) + 
  geom_line(position = position_dodge(width = 0)) + 
  geom_point(position = position_dodge(width = 0)) + 
  theme_ridges() + 
  scale_x_discrete(labels = c('Male Chairs','Yellen'),expand = c(.1,.1,.1,.7)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_label(data = toplotAny %>%
               mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
               filter(yellenTime == 1),#direction = 'y',min.segment.length = 100,
             aes(y = estimate,label = paste0(anyDaughters,': ',round(diff,3),'\n     (',round(se,2),')')),
             hjust = 1.1,
             direction = 'y',min.segment.length = Inf,
             size = 3) + 
  geom_segment(data = toplotAny %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate) %>%
                 distinct() %>%
                 mutate(mn = min(estimate),
                        mx = max(estimate)),
               inherit.aes = F,
               aes(y = mn,yend = mx),x = 2.15,xend = 2.15) + 
  geom_segment(data = toplotAny %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate,est,pval) %>%
                 distinct() %>%
                 summarise(yMid = min(estimate) + abs((diff(estimate)/2))),
               inherit.aes = F,
               x = 2.15,aes(y = yMid,yend = yMid),xend = 2.2) + 
  geom_label(data = toplotAny %>% 
               filter(yellenTime == 1) %>%
               select(estimate,est,pval,stdErr) %>%
               distinct() %>%
               summarise(yMid = min(estimate) + abs((diff(estimate)/2)),
                         est = abs(mean(est)),
                         pval = mean(pval),
                         se = mean(stdErr)),
             inherit.aes = F,
             x = 2.2,aes(y = yMid,label = paste0('Diff: ',round(est,3),'\n       (',round(se,2),')')),
             hjust = 0,size = 3) + 
  scale_color_manual(guide = 'none',name = 'Party',values = c('orange','brown')) + 
  scale_shape_discrete(guide = 'none',name = 'Party') + 
  labs(x = NULL,y = NULL,
       subtitle = 'Any Daughters')

toplotAnyM <- plot_cme(modAnyM,variables = 'fedResp',
                       condition = (c('yellenTime','anyDaughters')),draw = F)

toplotAnyM <- toplotAnyM %>%
  left_join(toplotAnyM %>%
              group_by(anyDaughters) %>%
              summarise(diff = diff(estimate),
                        se = sqrt(sum(std.error^2))) %>%
              ungroup()) %>%
  bind_cols(modAnyM$coeftable %>%
              data.frame() %>%
              mutate(vars = row.names(.)) %>%
              filter(grepl('.*:.*:.*',vars)) %>%
              as_tibble() %>%
              select(est = Estimate,pval = Pr...t..,stdErr = Std..Error))

pAnyM <- toplotAnyM %>%
  mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
  ggplot(aes(x = factor(yellenTime),y = estimate,group = anyDaughters,color = anyDaughters,shape = anyDaughters)) + 
  geom_errorbar(aes(ymin = conf.low,ymax = conf.high),width = 0,position = position_dodge(width = 0)) + 
  geom_line(position = position_dodge(width = 0)) + 
  geom_point(position = position_dodge(width = 0)) + 
  theme_ridges() + 
  scale_x_discrete(labels = c('Male Chairs','Yellen'),expand = c(.1,.1,.1,.7)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_label(data = toplotAnyM %>%
               mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
               filter(yellenTime == 1),#direction = 'y',min.segment.length = 100,
             aes(y = estimate,label = paste0(anyDaughters,': ',round(diff,3),'\n     (',round(se,2),')')),
             hjust = 1.1,size = 3) + 
  geom_segment(data = toplotAnyM %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate) %>%
                 distinct() %>%
                 mutate(mn = min(estimate),
                        mx = max(estimate)),
               inherit.aes = F,
               aes(y = mn,yend = mx),x = 2.15,xend = 2.15) + 
  geom_segment(data = toplotAnyM %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate,est,pval) %>%
                 distinct() %>%
                 summarise(yMid = min(estimate) + abs((diff(estimate)/2))),
               inherit.aes = F,
               x = 2.15,aes(y = yMid,yend = yMid),xend = 2.2) + 
  geom_label(data = toplotAnyM %>% 
               filter(yellenTime == 1) %>%
               select(estimate,est,pval,stdErr) %>%
               distinct() %>%
               # group_by(est,pval) %>%
               summarise(yMid = min(estimate) + abs((diff(estimate)/2)),
                         est = abs(mean(est)),
                         pval = mean(pval),
                         se = mean(stdErr)),
             inherit.aes = F,
             x = 2.2,aes(y = yMid,label = paste0('Diff: ',round(est,3),'\n       (',round(se,2),')')),
             hjust = 0,size = 3) + 
  scale_color_manual(guide = 'none',name = 'Party',values = c('orange','brown')) + 
  scale_shape_discrete(guide = 'none',name = 'Party') + 
  labs(x = NULL,y = NULL,
       subtitle = 'Any Daughters: Men')


toplotAnyF <- plot_cme(modAnyF,variables = 'fedResp',
                       condition = (c('yellenTime','anyDaughters')),draw = F)

toplotAnyF <- toplotAnyF %>%
  left_join(toplotAnyF %>%
              group_by(anyDaughters) %>%
              summarise(diff = diff(estimate),
                        se = sqrt(sum(std.error^2))) %>%
              ungroup()) %>%
  bind_cols(modAnyF$coeftable %>%
              data.frame() %>%
              mutate(vars = row.names(.)) %>%
              filter(grepl('.*:.*:.*',vars)) %>%
              as_tibble() %>%
              select(est = Estimate,pval = Pr...t..,stdErr = Std..Error))

pAnyF <- toplotAnyF %>%
  mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
  ggplot(aes(x = factor(yellenTime),y = estimate,group = anyDaughters,color = anyDaughters,shape = anyDaughters)) + 
  geom_errorbar(aes(ymin = conf.low,ymax = conf.high),width = 0,position = position_dodge(width = 0)) + 
  geom_line(position = position_dodge(width = 0)) + 
  geom_point(position = position_dodge(width = 0)) + 
  theme_ridges() + 
  scale_x_discrete(labels = c('Male Chairs','Yellen'),expand = c(.1,.1,.1,.7)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_label_repel(data = toplotAnyF %>%
               mutate(anyDaughters = ifelse(anyDaughters == 0,'None','1+')) %>%
               filter(yellenTime == 1),#direction = 'y',min.segment.length = 100,
             aes(y = estimate,label = paste0(anyDaughters,': ',round(diff,3),'\n     (',round(se,2),')')),
             nudge_x = -.1,hjust = 1,direction = 'y',size = 3,min.segment.length = Inf) + 
  geom_segment(data = toplotAnyF %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate) %>%
                 distinct() %>%
                 mutate(mn = min(estimate),
                        mx = max(estimate)),
               inherit.aes = F,
               aes(y = mn,yend = mx),x = 2.15,xend = 2.15) + 
  geom_segment(data = toplotAnyF %>% 
                 filter(yellenTime == 1) %>%
                 select(estimate,est,pval) %>%
                 distinct() %>%
                 summarise(yMid = min(estimate) + abs((diff(estimate)/2))),
               inherit.aes = F,
               x = 2.15,aes(y = yMid,yend = yMid),xend = 2.2) + 
  geom_label(data = toplotAnyF %>% 
               filter(yellenTime == 1) %>%
               select(estimate,est,pval,stdErr) %>%
               distinct() %>%
               # group_by(est,pval) %>%
               summarise(yMid = min(estimate) + abs((diff(estimate)/2)),
                         est = abs(mean(est)),
                         pval = mean(pval),
                         se = mean(stdErr)),
             inherit.aes = F,
             x = 2.2,aes(y = yMid,label = paste0('Diff: ',round(est,3),'\n       (',round(se,2),')')),
             hjust = 0,size = 3) + 
  scale_color_manual(guide = 'none',name = 'Party',values = c('orange','brown')) + 
  scale_shape_discrete(guide = 'none',name = 'Party') + 
  labs(x = NULL,y = NULL,
       subtitle = 'Any Daughters: Women')

pdf('./output/figures/MS_figure_8.pdf',width = 8,height = 5)
pAny + (pAnyM / pAnyF) + plot_layout(widths = c(4,2))
dev.off()


summary(modAny3 <- feols(as.formula(paste0('interruptor ~ fedResp*yellenTime*anyDaughters*gender',
                                           ' + nSons + interrupted + poly(year,3) + log(tot_utterances) + log(nchars_lag)',
                                           '| opensecretsID + chamber')),
                         utterance_level %>%
                           mutate(yellenTime = ifelse(yellenTime,1,0),
                                  anyDaughters = ifelse(nDaughters > 0,1,0)) %>%
                           filter(ind > mind,
                                  all > 30),
                         cluster = c('opensecretsID')))

etable(modAny,modAnyF,modAnyM,modAny3,depvar = F,digits = 3,
       signif.code = c('***' = .001,'**' = .01,'*' = .05,'\\dag' = .1),
       replace = T,headers = c('Combined','Female Subset','Male Subset','4-way'),
       file = './output/tables/SI_table_8.tex')

# EOF